package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.dto.*;
import com.sky.entity.*;
import com.sky.exception.AddressBookBusinessException;
import com.sky.exception.OrderBusinessException;
import com.sky.exception.ShoppingCartBusinessException;
import com.sky.mapper.*;
import com.sky.result.PageResult;
import com.sky.service.OrderService;
import com.sky.utils.WeChatPayUtil;
import com.sky.vo.*;
import com.sky.webSocket.WebSocketServer;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.*;

import static com.sky.entity.Orders.CANCELLED;
import static com.sky.entity.Orders.CONFIRMED;

@Service
public class OrderServiceImpl implements OrderService {

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private AddressBookMapper addressBookMapper;

    @Autowired
    private ShoppingCartMapper shoppingCartMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private OrderDetailMapper orderDetailMapper;

    @Autowired
    private WeChatPayUtil weChatPayUtil;

    @Autowired
    private WebSocketServer webSocketServer;


    private Orders orders;

    /**
     * 用户下单
     *
     * @param ordersSubmitDTO
     * @return
     */
    @Transactional
    @Override
    public OrderSubmitVO submit(OrdersSubmitDTO ordersSubmitDTO) {
        //判断提交信息合法性
        //地址信息校验
        AddressBook addressBook = addressBookMapper.getById(ordersSubmitDTO.getAddressBookId());
        if (Objects.isNull(addressBook)) {
            throw new AddressBookBusinessException(MessageConstant.ADDRESS_BOOK_IS_NULL);
        }
        //购物车信息校验
        Long userId = BaseContext.getCurrentId();
        ShoppingCart shoppingCart = new ShoppingCart();
        shoppingCart.setUserId(userId);
        List<ShoppingCart> shoppingCarts = shoppingCartMapper.queryList(shoppingCart);
        if (Objects.isNull(shoppingCarts)) {
            throw new ShoppingCartBusinessException(MessageConstant.SHOPPING_CART_IS_NULL);
        }
        //向订单表插入信息
        Orders orders = new Orders();
        BeanUtils.copyProperties(ordersSubmitDTO, orders);
        //订单状态
        orders.setStatus(Orders.PENDING_PAYMENT);
        //支付状态
        orders.setPayStatus(Orders.UN_PAID);
        //用户id
        orders.setUserId(BaseContext.getCurrentId());
        //时间
        LocalDateTime now = LocalDateTime.now();
        orders.setOrderTime(now);
        //手机号
        orders.setPhone(addressBook.getPhone());
        //地址
        String address = addressBook.getProvinceName() + addressBook.getCityName()
                + addressBook.getDistrictName() + addressBook.getDetail();
        orders.setAddress(address);
        //订单id
        String number = UUID.randomUUID().toString().replaceAll("-", "").substring(0, 10);
        orders.setNumber(number);
        //收获人
        orders.setConsignee(addressBook.getConsignee());
        //orders.setUserName();
        //插入
        this.orders = orders;
        orderMapper.insert(orders);

        //向订单细节表中插入信息，与订单表是一对多的关系
        List<OrderDetail> details = new ArrayList<>();
        for (ShoppingCart cart : shoppingCarts) {
            OrderDetail detail = new OrderDetail();
            BeanUtils.copyProperties(cart, detail);
            detail.setOrderId(orders.getId());
            //添加到数据集合
            details.add(detail);
        }
        //清空购物车
        shoppingCartMapper.delete(shoppingCart);
        //遍历购物车插入细节表
        orderDetailMapper.insertBatchs(details);
        //生成用于返回前台的信息
        OrderSubmitVO orderSubmitVO = OrderSubmitVO.builder()
                .orderTime(now)
                .orderAmount(ordersSubmitDTO.getAmount())
                .orderNumber(number)
                .build();
        //封装数据返回
        return orderSubmitVO;
    }

    /**
     * 订单支付
     *
     * @param ordersPaymentDTO
     * @return
     */
    public OrderPaymentVO payment(OrdersPaymentDTO ordersPaymentDTO) throws Exception {
        // 当前登录用户id
        Long userId = BaseContext.getCurrentId();
        User user = userMapper.getById(userId);

        //调用微信支付接口，生成预支付交易单
//        JSONObject jsonObject = weChatPayUtil.pay(
//                ordersPaymentDTO.getOrderNumber(), //商户订单号
//                new BigDecimal(0.01), //支付金额，单位 元
//                "苍穹外卖订单", //商品描述
//                user.getOpenid() //微信用户的openid
//        );
//
//        if (jsonObject.getString("code") != null && jsonObject.getString("code").equals("ORDERPAID")) {
//            throw new OrderBusinessException("该订单已支付");
//        }
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("code", "ORDERPAID");
        OrderPaymentVO vo = jsonObject.toJavaObject(OrderPaymentVO.class);
        vo.setPackageStr(jsonObject.getString("package"));
        Integer OrderPaidStatus = Orders.PAID;//支付状态，已支付
        Integer OrderStatus = Orders.TO_BE_CONFIRMED;  //订单状态，待接单
        LocalDateTime check_out_time = LocalDateTime.now();//更新支付时间
        orderMapper.updateStatus(OrderStatus, OrderPaidStatus, check_out_time, this.orders.getId());

        //通过websocket向客户端浏览器推送消息 type orderId content
        Map map = new HashMap();
        map.put("type", 1);
        map.put("orderId", this.orders.getId());
        map.put("content", "订单号：" + this.orders.getNumber());
        String json = JSON.toJSONString(map);
        webSocketServer.sendToAllClient(json);
        vo.setPackageStr(jsonObject.getString("package"));

        return vo;
    }

    /**
     * 支付成功，修改订单状态
     *
     * @param outTradeNo
     */
    public void paySuccess(String outTradeNo) {

        // 根据订单号查询订单
        Orders ordersDB = orderMapper.getByNumber(outTradeNo);

        // 根据订单id更新订单的状态、支付方式、支付状态、结账时间
        Orders orders = Orders.builder()
                .id(ordersDB.getId())
                .status(Orders.TO_BE_CONFIRMED)
                .payStatus(Orders.PAID)
                .checkoutTime(LocalDateTime.now())
                .build();

        orderMapper.update(orders);
    }

    /**
     * 历史订单查询
     *
     * @return
     */
    @Override
    public PageResult queryByHistoryOrders(int page, int pageSize, Integer status) {
        //TODO 这里没看懂答案
        //查询用户所有订单
        Orders orders = Orders.builder()
                .userId(BaseContext.getCurrentId())
                .status(status)
                .build();

        PageHelper.startPage(page, pageSize);
        Page<Orders> ordersPage = orderMapper.queryByHistoryOrders(orders);
        //返回对象
        List<OrderVO> list = new ArrayList<>();
        //查询用户的订单的详细信息
        for (Orders ordersForDetail : ordersPage) {
            OrderVO orderVO = new OrderVO();
            List<OrderDetail> orderDetails = orderDetailMapper.queryByOrderId(ordersForDetail.getId());
            BeanUtils.copyProperties(ordersForDetail, orderVO);
            orderVO.setOrderDetailList(orderDetails);

            list.add(orderVO);
        }
        PageResult pageResult = new PageResult(ordersPage.getTotal(), list);
        return pageResult;
    }

    /**
     * 查询订单细节
     *
     * @param id
     * @return
     */
    @Override
    public OrderVO queryById(Long id) {
        //查询订单信息
        Orders orders = orderMapper.queryById(id);

        OrderVO orderVO = new OrderVO();
        BeanUtils.copyProperties(orders, orderVO);
        //查询订单细节
        List<OrderDetail> orderDetails = orderDetailMapper.queryByOrderId(id);
        orderVO.setOrderDetailList(orderDetails);
        return orderVO;
    }

    /**
     * 根据id取消订单
     *
     * @param id
     * @return
     */
    @Override
    public void cancel(Long id) {
        //用户只能在待接单之前取消，之后需要与商家沟通
        Orders queryById = orderMapper.queryById(id);
        if (queryById.getStatus() > 2) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        Orders orders = Orders.builder()
                .id(id)
                .cancelTime(LocalDateTime.now())
                .cancelReason("用户取消")
                .status(CANCELLED)
                .build();

        orderMapper.cancel(orders);
    }

    /**
     * 再来一单
     * <p>
     * 就是将取消的订单重新加入购物车里
     *
     * @param id
     * @return
     */
    @Override
    public void repetition(Long id) {
        //根据订单id,把订单详情的菜品查出来加入购物车中
        List<OrderDetail> orderDetails = orderDetailMapper.queryByOrderId(id);
        for (OrderDetail detail : orderDetails) {
            ShoppingCart shoppingCart = ShoppingCart.builder()
                    .name(detail.getName())
                    .userId(BaseContext.getCurrentId())
                    .number(detail.getNumber())
                    .amount(detail.getAmount())
                    .image(detail.getImage())
                    .createTime(LocalDateTime.now())
                    .build();
            //设置套餐或菜品
            if (detail.getDishId() == null) {
                shoppingCart.setSetmealId(detail.getSetmealId());
            } else {
                shoppingCart.setDishId(detail.getDishId());
                shoppingCart.setDishFlavor(detail.getDishFlavor());
            }
            shoppingCartMapper.insert(shoppingCart);
        }
    }

    /**
     * 商家查询订单
     *
     * @param ordersPageQueryDTO
     * @return
     */
    @Override
    public PageResult queryByPage(OrdersPageQueryDTO ordersPageQueryDTO) {
        PageHelper.startPage(ordersPageQueryDTO.getPage(), ordersPageQueryDTO.getPageSize());
        //查询订单
        Page<Orders> page = orderMapper.queryByPage(ordersPageQueryDTO);
        //用于遍历订单信息
        List<Orders> ordersList = page.getResult();
        //用于封装vo对象
        List<OrderVO> orderVOList = new ArrayList<>();
        if (ordersList != null) {
            for (Orders orders : ordersList) {
                //查询订单详情，封装到orderVo对象中
                OrderVO orderVO = new OrderVO();
                BeanUtils.copyProperties(orders, orderVO);
                List<OrderDetail> details = orderDetailMapper.queryByOrderId(orders.getId());
                orderVO.setOrderDetailList(details);

                //展示菜品信息
                String dishNames = "";
                for (OrderDetail orderDetail : details) {
                    if (dishNames == "") {
                        dishNames = orderDetail.getName();
                    } else {
                        dishNames = dishNames + "," + orderDetail.getName();
                    }
                }

                orderVO.setOrderDishes(dishNames);
                orderVOList.add(orderVO);
            }
        }

        //返回分页结果
        PageResult pageResult = new PageResult();
        pageResult.setTotal(page.getTotal());
        pageResult.setRecords(orderVOList);
        return pageResult;
    }

    /**
     * 接单
     *
     * @param ordersConfirmDTO
     * @return
     */
    @Override
    public void confirm(OrdersConfirmDTO ordersConfirmDTO) {
        Orders queryById = orderMapper.queryById(ordersConfirmDTO.getId());
        if (queryById == null || queryById.getStatus() != 2) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        Orders orders = Orders.builder()
                .id(ordersConfirmDTO.getId())
                .status(CONFIRMED)
                .build();

        orderMapper.updateData(orders);

    }

    /**
     * 拒单
     *
     * @param ordersRejectionDTO
     * @return
     */
    @Override
    public void rejection(OrdersRejectionDTO ordersRejectionDTO) {
        Orders queryById = orderMapper.queryById(ordersRejectionDTO.getId());
        if (queryById == null || queryById.getStatus() != 2) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        Orders orders = Orders.builder()
                .id(ordersRejectionDTO.getId())
                .rejectionReason(ordersRejectionDTO.getRejectionReason())
                .status(CANCELLED)
                .build();
        orderMapper.updateData(orders);
    }

    /**
     * 商家取消订单
     *
     * @param ordersCancelDTO
     * @return
     */
    @Override
    public void cancelByAdmin(OrdersCancelDTO ordersCancelDTO) {
        Orders queryById = orderMapper.queryById(ordersCancelDTO.getId());
        //查询订单信息
        if (queryById == null) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        //更新订单信息
        Orders orders = Orders.builder()
                .id(ordersCancelDTO.getId())
                .cancelReason(ordersCancelDTO.getCancelReason())
                .cancelTime(LocalDateTime.now())
                .status(CANCELLED)
                .build();

        orderMapper.updateData(orders);
    }

    /**
     * 订单派送
     *
     * @param id
     * @return
     */
    @Override
    public void delivery(Long id) {
        Orders queryById = orderMapper.queryById(id);
        //只有订单状态为已接单，并且订单不为空才能派送
        if (queryById == null || queryById.getStatus() != CONFIRMED) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        ;

        //更新订单状态
        Orders orders = Orders.builder()
                .id(id)
                .status(Orders.DELIVERY_IN_PROGRESS)
                .build();

        orderMapper.updateData(orders);

    }

    /**
     * 完成订单
     *
     * @param id
     * @return
     */
    @Override
    public void complete(Long id) {
        //查询订单信息
        Orders queryById = orderMapper.queryById(id);

        //如果订单 不存在 或者订单状态不是 派送中 ，抛异常
        if (queryById == null || queryById.getStatus() != Orders.DELIVERY_IN_PROGRESS) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        //更新订单数据
        Orders orders = Orders.builder()
                .id(id)
                .status(Orders.COMPLETED)
                .deliveryTime(LocalDateTime.now())
                .build();

        orderMapper.updateData(orders);
    }

    /**
     * 各个状态的订单数量统计
     *
     * @return
     */
    @Override
    public OrderStatisticsVO statistics() {
        //查询所有订单状态
        Page<Orders> ordersPage = orderMapper.queryByPage(new OrdersPageQueryDTO());
        List<Orders> list = ordersPage.getResult();

        //统计数量
        //待接单数量
        Integer toBeConfirmed = 0;
        //待派送数量
        Integer confirmed = 0;
        //派送中数量
        Integer deliveryInProgress = 0;

        for (Orders orders : list) {

            if (orders.getStatus() == Orders.TO_BE_CONFIRMED) {
                toBeConfirmed++;
            } else if (orders.getStatus() == Orders.CONFIRMED) {
                confirmed++;
            } else if (orders.getStatus() == Orders.DELIVERY_IN_PROGRESS) {
                deliveryInProgress++;
            }
        }
        OrderStatisticsVO orderStatisticsVO = new OrderStatisticsVO();
        orderStatisticsVO.setToBeConfirmed(toBeConfirmed);
        orderStatisticsVO.setConfirmed(confirmed);
        orderStatisticsVO.setDeliveryInProgress(deliveryInProgress);

        return orderStatisticsVO;
    }

    /**
     * 用户催单
     *
     * @param id
     * @return
     */
    @Override
    public void reminder(Long id) {
        //查询订单防止绕过前端发送请求
        Orders queryById = orderMapper.queryById(id);
        if (queryById == null) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }

        //通过websocket向客户端浏览器推送消息 type orderId content
        Map map = new HashMap();
        map.put("type", 2);
        map.put("orderId", queryById.getId());
        map.put("content", "订单号：" + queryById.getNumber());
        String json = JSON.toJSONString(map);
        webSocketServer.sendToAllClient(json);

    }


}
